using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors.Popup;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using ChuanPlus.DAO;
using DevExpress.Xpo;
using ChuanPlus.Reports;
namespace ChuanPlus.FormControl
{
    public partial class ControlProduction : DevExpress.XtraEditors.XtraUserControl
    {
        
        DataTable m_dtMaterialTable = new DataTable();
        Stock EndProduct = null;
        
        public ControlProduction()
        {
            InitializeComponent();
            dateProduction.DateTime = DateTime.Today;
            m_dtMaterialTable.Columns.Add(new DataColumn("ItemCode"));
            m_dtMaterialTable.Columns.Add(new DataColumn("Description"));
            m_dtMaterialTable.Columns.Add(new DataColumn("Quantity"));
            m_dtMaterialTable.Columns.Add(new DataColumn("ID"));
            m_dtMaterialTable.Columns.Add(new DataColumn("DistributorName"));
            m_dtMaterialTable.Columns.Add(new DataColumn("AvaiQty"));
            DataColumn[] keys = new DataColumn[1];
            keys[0] = m_dtMaterialTable.Columns[3];
            m_dtMaterialTable.PrimaryKey = keys;
            gridBottom.DataSource = m_dtMaterialTable;
            xpColProduct.AddRange(StockDAO.ListProductByWarehouseName("Stock"));
        }     

        private void gridView2_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "ItemCode")
            {
                // get select row in look up edit

                Product product = (Product)repositoryItemLookUpEdit1.GetDataSourceRowByKeyValue(e.Value);
                if (product != null) // if e.value cannot get product
                {
                    DataRow row = gridView2.GetFocusedDataRow();
                    row["Description"] = product.Description;
                    row["Quantity"] = 0;
                    row["ID"] = product.ID;
                    row["AvaiQty"] = DAO.StockDAO.GetStock(product.ID, 2).QtyBalance;
                }
            }
            if (e.Column.FieldName == "Quantity")
            {
                if (e.Value.Equals(""))
                {
                    DataRow row = gridView2.GetFocusedDataRow();
                    row["Quantity"] = 0;
                }
            }
        }

        private void gridView2_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            DataRow row = gridView2.GetFocusedDataRow();
            int DSIndex = gridView2.GetDataSourceRowIndex(gridView2.FocusedRowHandle);          
            string newItemCode = row["ItemCode"].ToString();
            for(int i = 0; i< m_dtMaterialTable.Rows.Count; i++)
            {
                if(i != DSIndex)    // exclude current item code
                {
                    DataRow item = m_dtMaterialTable.Rows[i];
                    if (item["ItemCode"].ToString() == newItemCode)
                    {
                        e.Valid = false;
                        e.ErrorText = "This material is choosen already. ";
                    }
                }
            }        
               
        }

        private void gridView2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {                
                gridView2.DeleteRow(gridView2.FocusedRowHandle);
            }
        }

        private void gridView2_DoubleClick(object sender, EventArgs e)
        {
            gridView2.DeleteRow(gridView2.FocusedRowHandle);
        }

        private void gridLUProduct_Properties_EditValueChanged(object sender, EventArgs e)
        {
            if (gridLookUpEdit1View.GetSelectedRows().Length > 0)
            {
                Product product = gridLUProduct.Properties.GetKeyValue(gridLookUpEdit1View.GetSelectedRows()[0]) as Product;
                EndProduct = StockDAO.GetStock(product.ID, 2);
            }
        }


        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!FormValidation()) return;
            DialogResult res = MessageBox.Show("Are you sure want to create new production","Message",MessageBoxButtons.OK,MessageBoxIcon.Question);
            if(res == DialogResult.OK)
            {
                
                try
                {
                    // get summary value from footer row
                    double total = Convert.ToDouble(gridView2.Columns["Quantity"].SummaryItem.SummaryValue);
                    Production production = new Production(Session.DefaultSession, EndProduct, dateProduction.DateTime,
                                total, "", 0, Convert.ToDouble(textLoss.Text), memoRemarks.Text, "H");
                    Stock material_stock;
                    ProductionDetails productionDetails = null;
                    foreach (DataRow row in m_dtMaterialTable.Rows)
                    {
                        material_stock = StockDAO.GetStock(Convert.ToInt32(row["ID"]), 2);
                        productionDetails = new ProductionDetails(Session.DefaultSession, material_stock, "", Convert.ToDouble(row["Quantity"]));
                        production.ProductionDetails.Add(productionDetails);
                    }
                    production.Save();
                    MessageBox.Show("New production has been added","Message", MessageBoxButtons.OK,MessageBoxIcon.Information);
                    Reset();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    throw;
                }
            }
        }
        private bool FormValidation()
        { 
            if (gridLUProduct.Text == "")
            {
                MessageBox.Show("Please select output product", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                gridLUProduct.Focus();
                return false;
            }
            if (dateProduction.Text == "")
            {
                MessageBox.Show("Please pick a production date", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                dateProduction.Focus();
                return false;
            }
            if (m_dtMaterialTable.Rows.Count <= 0)
            {
                MessageBox.Show("Please select meterial","Message",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return false;
            }
            int DSIndex = validateQty();
            if (DSIndex != -1) 
            {
                gridView2.FocusedRowHandle = gridView1.GetRowHandle(DSIndex);
                return false;
            }
            double total = Convert.ToDouble(gridView2.Columns["Quantity"].SummaryItem.SummaryValue);
            if (Convert.ToDouble(textLoss.Text) > total)
            {
                MessageBox.Show("Total quantity should be greater than loss", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                textLoss.Focus();
                return false;
            }
            return true;
        }
       
        private int validateQty()
        {
            for (int i = 0; i < m_dtMaterialTable.Rows.Count; i++)
            {
                DataRow row = m_dtMaterialTable.Rows[i];
                if (Convert.ToDouble(row["Quantity"]) <= 0)
                {
                    MessageBox.Show("Quantity should be greater than 0","Message", MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return i;
                }
            }
            return -1;
        }
        private void btnReset_Click(object sender, EventArgs e)
        {
            Reset();
        }
        private void Reset()
        {
            gridLUProduct.Text = "";
            dateProduction.DateTime = DateTime.Now.Date;
            textLoss.Text = "0";
            memoRemarks.Text = "";
            m_dtMaterialTable.Rows.Clear();
            gridBottom.RefreshDataSource();
        }

        private void gridView2_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            if (gridView2.FocusedColumn.FieldName == "Quantity")
            {
                DataRow row = gridView2.GetFocusedDataRow();
                if (Convert.ToDouble(e.Value) > Convert.ToDouble(row["AvaiQty"]))
                {
                    e.Valid = false;
                    e.ErrorText = "Maximum is " + row["AvaiQty"].ToString();
                }
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            production_master rpt = new production_master();
            rpt.Parameters[0].Value = 9;
            rpt.ShowPreview();
        }

        private void repositoryItemLookUpEdit1_EditValueChanged(object sender, EventArgs e)
        {
            
        }
    }        
}
